﻿using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Ultima.Xna.SceneManagement
{
    public class LoadingScene : BaseScene
    {
        IScene _scene;
        Texture2D _progressBar;
        SpriteFont _font;
        Color _progressBarColor = Color.Green;
        
        string _loadingString = "Loading.";
        float _percentComplete;
        bool _isLoaded;

        public LoadingScene(Game game, IScene scene)
            : base(game, false)
        {
            _scene = scene;
            _scene.ProgressUpdated += new EventHandler<ProgressUpdateEventArgs>(OnLoadingProgressUpdated);
            _scene.StatusUpdate += new EventHandler<StatusUpdateEventArgs>(OnLoadingStatusUpdate);
        }

        protected virtual void OnLoadingStatusUpdate(object sender, StatusUpdateEventArgs e)
        {
            _loadingString = e.Status;
        }

        protected virtual void OnLoadingProgressUpdated(object sender, ProgressUpdateEventArgs e)
        {
            _percentComplete = (float)e.ProgressPercentage / 100f;
        }

        public override void Intitialize()
        {
            base.Intitialize();

            Color[] data = new Color[] { Color.White };

            _progressBar = new Texture2D(GraphicsDevice, 1, 1);
            _progressBar.SetData<Color>(data);

            _font = Content.Load<SpriteFont>("Fonts\\LoadingScene");

            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o)
            {
                _scene.Intitialize();
                _scene.IsInitialized = true;
                _isLoaded = true;
            }));
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (_isLoaded)
            {
                _isLoaded = false;
                SceneManager.CurrentScene = _scene;
            }
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            SpriteBatch.Begin();

            PresentationParameters pp = SpriteBatch.GraphicsDevice.PresentationParameters;

            int centerX = pp.BackBufferWidth / 2;
            int centerY = pp.BackBufferHeight / 2;

            SpriteBatch.DrawString(_font, _loadingString, new Vector2(centerX - _font.MeasureString(_loadingString).X / 2f, centerY), Color.White);
            SpriteBatch.Draw(_progressBar, new Rectangle(0, pp.BackBufferHeight - 20, (int)(pp.BackBufferWidth * _percentComplete), 20), _progressBarColor);

            SpriteBatch.End();
        }

        public override void Dispose()
        {
            _scene.ProgressUpdated -= new EventHandler<ProgressUpdateEventArgs>(OnLoadingProgressUpdated);
            _progressBar.Dispose();

            base.Dispose();
        }
    }
}
